<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<cl-export-btn :columns="Table?.columns" />
			<!-- 新增按钮 -->
			<!-- <cl-add-btn /> -->
			<!-- 删除按钮 -->
			<!-- <cl-multi-delete-btn /> -->
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<!-- 插槽的渲染方式 #[component.name] -->
				 <template #slot-order-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								jumpToOrder(scope.row.studentId);
							}
						"
					>
						开订单
					</el-button>
				</template>
                <template #slot-prescription-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								openPrescription(scope.row.studentId, scope.row);
							}
						"
					>
						开处方
					</el-button>
				</template>
				<template #slot-editprescription-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								openPrescription(scope.row.studentId, scope.row);
							}
						"
					>
						修改处方
					</el-button>
				</template>
                <template #slot-report-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								showReport(scope.row.studentId);
							}
						"
					>
						报告
					</el-button>
				</template>
				<template #slot-sign-btn="{ scope }">
					<el-button
						type="success"
						:disabled="scope.row.appointmentStatus === 1"
						@click="
							() => {
								appointCome(scope.row.id);
							}
						"
					>
						{{ scope.row.appointmentStatus === 1 ? '已到店' : '签到' }}
					</el-button>
				</template>
				<template #slot-change-btn="{ scope }">
					<el-button
						type="success"
						@click="
							() => {
								showAppointDialog(scope.row.studentId);
							}
						"
						>改约</el-button
					>
				</template>
				<template #slot-cancle-btn="{ scope }">
					<el-button
						type="info"
						@click="
							() => {
								cancleAppoint(scope.row.id);
							}
						"
						>取消</el-button
					>
				</template>
				<template #slot-edit-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								editStudent(scope.row.studentId);
							}
						"
						>学员信息</el-button
					>
				</template>
				<template #slot-profile-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								profileStudent(scope.row);
							}
						"
						>编辑档案</el-button
					>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
		<!-- 学员信息编辑弹窗 -->
		<student-edit-dialog
			v-model="studentDialog.visible"
			:student-id="studentDialog.studentId"
			@success="refresh"
		/>
		<!--档案编辑弹窗-->
		<profile-dialog
			v-model="profileDialog.visible"
			:student-id="profileDialog.studentId"
			:student-info="profileDialog.studentInfo"
			@saved="refresh"
		/>
		<week-appoint-dialog
			v-model="appointDialogVisible"
			:student-id="currentStudentId"
			@success="refresh"
		/>
        <el-dialog v-if="showReportDialog" v-model="showReportDialog">
            <shop-student-report
                :student-id="currentStudentId"
                @success="refresh"
            />
        </el-dialog>
		
		<shop-student-prescription
			v-model="showPrescriptionDialog"
			:student-id="currentStudentId"
			:appointObj="currentAppointObj"
			@success="refresh"
		/>
	</cl-crud>
	<!--预约弹窗-->
	
</template>

<script lang="ts" setup>
defineOptions({
	name: 'appointment-info'
});

import { useDict } from '/$/dict';
import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { reactive, watch, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useBase } from '/$/base';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProfileDialog from '../components/ProfileDialog.vue';
import StudentEditDialog from '../../student/components/ShopStudentEdit.vue';
import WeekAppointDialog from '../../student/components/WeekAppointDialog.vue';
import ShopStudentReport from '../../student/components/ShopStudentReport.vue';
import ShopStudentPrescription from '../../student/components/ShopStudentPrescription.vue';
import dayjs from 'dayjs';

const { service, setRefs, refs } = useCool();
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { user } = useBase();
const SalesList = ref([]);
const appointDialogVisible = ref(false);
const currentStudentId = ref(0);
const currentAppointObj = ref({});
const showReportDialog = ref(false);
const showPrescriptionDialog = ref(false);

// 学员信息弹窗数据
const studentDialog = reactive({
	visible: false,
	studentId: 0
});

// 档案信息弹窗数据可以简化为
const profileDialog = reactive({
	visible: false,
	studentId: 0,
	studentInfo: {}
});

// 选项
const options = reactive({
	appointmentStatus: [
		{ label: t('已预约'), value: 0 },
		{ label: t('已到店'), value: 1 },
		{ label: t('已改约'), value: 2 },
		{ label: t('已过期'), value: 3 },
		{ label: t('已取消'), value: 4 }
	],
	salesList: [],
	gender: [
		{ label: t('男'), value: 0 },
		{ label: t('女'), value: 1 },
		{ label: t('未知'), value: 2 }
	],
	appointmentType: [
		{ label: t('新客'), value: 0 },
		{ label: t('复查'), value: 1 }
	]
});
const { dict } = useDict();
// cl-upsert
const Upsert = useUpsert({
	items: [
		{
			label: t('预约状态'),
			prop: 'appointmentStatus',
			component: {
				name: 'el-radio-group',
				options: options.appointmentStatus
			},
			value: 0,
			required: true
		},
		{
			label: t('预约类型'),
			prop: 'appointmentType',
			component: {
				name: 'el-radio-group',
				options: options.appointmentType
			},
			value: 0,
			required: true
		},
		{
			label: t('备注'),
			prop: 'remark',
			component: {
				name: 'el-input',
				props: { type: 'textarea', rows: 4 }
			}
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
        {
			label: t('预约到店时间'),
			prop: 'appointmentTime',
			minWidth: 120,
			sortable: 'custom',
			component: {
				name: 'cl-date-text',
				props: {
					format: 'MM-DD HH:mm'
				}
			}
		},
		{ label: t('姓名'), prop: 'userName', minWidth: 120 },
        {
			label: t('年龄'),
			prop: 'userAge',
			minWidth: 60
		},
		{
			label: t('性别'),
			prop: 'userGender',
			minWidth: 60,
			formatter: (row, column, cellValue) => {
				const gender = options.gender.find(item => item.value === cellValue);
				return gender ? gender.label : cellValue;
			}
		},
		{ label: t('电话'), prop: 'userPhone', minWidth: 120 },
		{
			label: t('学员备注'),
			prop: 'userRemark',
			minWidth: 140,
			showOverflowTooltip: true
		},
		{
			label: t('预约类型'),
			prop: 'appointmentType',
			minWidth: 80,
			dict: options.appointmentType
		},
		{
			type: 'op',
			buttons: [],
			width: 300
		}
	]
});

// 定义当天的开始和结束时间
const todayStart = dayjs().startOf('day').format('YYYY-MM-DD');
const todayEnd = dayjs().endOf('day').format('YYYY-MM-DD');
const defaultDateRange = ref([todayStart, todayEnd]);

// cl-search
const Search = useSearch({
	items: [
		{
			prop: 'name',
			component: {
				name: 'el-input',
				props: { placeholder: '请输入姓名' }
			}
		},
        {
			prop: 'phone',
			component: {
				name: 'el-input',
				props: { placeholder: '请输入电话' }
			}
		},
        {
			prop: 'appointmentStatus',
			component: {
				name: 'cl-select',
				props: { options: options.appointmentStatus, placeholder: '已预约' }
			}
		},
		{
			prop: 'appointmentTime',
			component: {
				name: 'cl-date-picker',
				props: {
					type: 'daterange',
					valueFormat: 'YYYY-MM-DD',
					placeholder: ['开始时间', '结束时间'],
				}
			}
		}
	]
});
// cl-crud
const Crud = useCrud(
	{
		service: service.appointment.info,
		async onRefresh(params, { next, done, render }) {
			params.shopId = user.info?.shop;
			params.appointmentStatus = params.appointmentStatus || 1;
			params.comeType = 0;
			// if (!params.appointmentTimeStartTime && !params.appointmentTimeEndTime) {
			//     const today = new Date();
			// 	params.appointmentTimeStartTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
			// 	params.appointmentTimeEndTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
			// }
			if (!params.appointmentStatus) {
				params.appointmentStatus = 1;
			}
			Crud.value.params.shopId = params.shopId;
			Crud.value.params.comeType = params.comeType;
			Crud.value.params.appointmentStatus = params.appointmentStatus;

			const { list } = await next(params);

			// 渲染数据
			render(list);
		}
	},
	app => {
		app.refresh();
	}
);

watch(
	() => route.path,
	async newPath => {
		// 刷新数据
		await Crud.value?.refresh();
		// 更新表格列配置
		if (Table.value?.columns) {
			const opColumn = Table.value.columns.find(col => col.type === 'op');
			if (newPath.endsWith('todayShopAppoint')) {
				opColumn
					? (opColumn.buttons = [
							'slot-sign-btn',
							'slot-change-btn',
							'slot-edit-btn',
						])
					: '';
			} else if (newPath.endsWith('todayShopAppointSign')) {
				opColumn ? (opColumn.buttons = ['slot-prescription-btn', 'slot-report-btn']) : '';
			} else if (newPath.endsWith('finishShopAppoint')) {
				opColumn ? (opColumn.buttons = ['slot-order-btn', 'slot-editprescription-btn']) : '';
			} else {
				opColumn
					? (opColumn.buttons = [
							'slot-sign-btn',
							'slot-change-btn',
							'edit',
							'slot-edit-btn',
						])
					: '';
			}
		}
	},
	{ immediate: true }
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
// 已到店
async function appointCome(id: number) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要为该学员签到吗？'), t('签到确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});

		// 用户确认后继续签到流程
		await Crud.value?.service.appointCome({ appointId: id });
		ElMessage.success('签到成功');
		// 刷新表格数据
		Crud.value?.refresh();
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err !== 'cancel') {
			ElMessage.error(err.message || '签到失败');
		}
	}
}

// 编辑学员信息
function editStudent(id: number) {
	studentDialog.studentId = id;
	studentDialog.visible = true;
}

// 编辑学员档案
function profileStudent(row: any) {
	profileDialog.studentId = row.studentId;
	profileDialog.studentInfo = row;
	profileDialog.visible = true;
}
function showAppointDialog(studentId) {
	currentStudentId.value = studentId;
	appointDialogVisible.value = true;
}
// 取消预约
async function cancleAppoint(id: number) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要取消该预约吗？'), t('取消确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});
		// 用户确认后继续取消流程
		await Crud.value?.service.cancelAppoint({ appointId: id });
		ElMessage.success('取消成功');
		Crud.value?.refresh();
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err!== 'cancel') {
			ElMessage.error(err.message || '取消失败');
			return;
		}
	}
}

// 打开报告
async function showReport(studentId: number) {
    currentStudentId.value = studentId;
	showReportDialog.value = true;
}
// 打开处方
async function openPrescription(studentId: number, appoint: object) {
    currentStudentId.value = studentId;
	currentAppointObj.value = appoint;
    showPrescriptionDialog.value = true;
}
// 跳转到订单页面
async function jumpToOrder(studentId: number) {
	try {
        // 跳转到 order/info 页面，并可以传递 studentId 作为参数
        await router.push({ path: `/order/info`, query: { studentId } });
    } catch (error) {
        console.error('路由跳转失败:', error);
    }
}
</script>
<style scoped>
.appoint-item {
	margin-top: 5px;
	margin-bottom: 20px;
}
.timeList {
	margin-top: 20px;
}

.time-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.time-slot {
	width: 45%;
	padding: 10px;
	text-align: center;
	border-radius: 4px;
	cursor: pointer;
	background-color: #fff;
	border: 1px solid #dcdfe6;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	background-color: #fde2e2;
	color: #f56c6c;
	cursor: not-allowed;
}

.time-slot.selected {
	background-color: #fff;
	border: 1px solid #409eff;
	color: #409eff;
}
</style>
